package com.example.zxw.ui.news

import androidx.lifecycle.viewModelScope
import com.example.zxw.datalayer.NewsRepo
import com.example.zxw.entity.ChannelEntity
import com.example.zxw.entity.HotWordsEntity
import com.example.zxw.net.BaseViewModel
import com.example.zxw.net.NewsApiService.getChannelList
import com.example.zxw.net.NewsApiService.getHotWords
import com.example.zxw.net.result.CommonResult
import com.fmt.mvi.learn.gobal.log
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch


data class NewsPageData(
    val hotWordsList: List<HotWordsEntity> = emptyList(),
    val channelEntityList: List<ChannelEntity> = emptyList(),
    val isLoading: Boolean = false,
    val isSuccess: Boolean = false,
    val errorMsg: String = ""
)

class NewsViewModel : BaseViewModel() {

    private val newsRepo by lazy { NewsRepo() }
    private val _newsPageUiState = MutableStateFlow(NewsPageData(isLoading = true))
    val newPageUiState: StateFlow<NewsPageData> = _newsPageUiState.asStateFlow()

    init {
        getChannelList()
        getHotWords()
    }

    private fun getHotWords() {
        viewModelScope.launch {
            newsRepo.getHotWords().let { result ->
                when (result) {
                    is CommonResult.Success -> {
                        _newsPageUiState.update { state ->
                            state.copy(hotWordsList = result.data)
                        }
                    }

                    is CommonResult.Error -> {
                        result.exception.log("YYYYY")
                    }
                }
            }
        }
    }

    private fun getChannelList() {
        viewModelScope.launch {
            _newsPageUiState.update { it.copy(isLoading = true) }
            newsRepo.getChannelList().let { result ->
                when (result) {
                    is CommonResult.Success -> {
                        _newsPageUiState.update { state ->
                            state.copy(isLoading = false, isSuccess = true, channelEntityList = result.data)
                        }
                    }

                    is CommonResult.Error -> {
                        _newsPageUiState.update { state ->
                            state.copy(isLoading = false, isSuccess = false, errorMsg = "请求失败")
                        }
                    }
                }
            }
        }
    }
}